﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using YAPACS.Organizations;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.Report;

public class GetRevisitView(ICurrentUserOrganization currentUserOrganization,
    IRepository<ApplicationUser, Guid> userRepoitory) : WorkflowBase, IGetRevisitView, ITransientDependency
{
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<ApplicationUser, Guid> _userRepoitory = userRepoitory;
    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        WorkflowOutput workflowOutput = new()
        {
            Success = true,
            View = await Extensions.GetResourceStringAsync("Resources.Report.revisit-view.json"),
            ViewTitle = "患者回访",
            ViewWidth = "50%"
        };
        const string key = "Report";
        if (input.ContainsKey(key) && input.GetValueOrDefault(key) is BusinessObjects.Exams.Report report)
        {
            bool readOnly = true;
            var user = await _userRepoitory.GetAsync(_currentUserOrganization.UserId);
            if (report.InitialWritingDoctor == user || report.ReportDoctor == user || report.AuditDoctor == user || report.ReviewDoctor == user)
            {
                workflowOutput.NextAction = "报告-回访";
                readOnly = false;
            }
            workflowOutput.Data = new
            {
                report.Exam.Patient.Name,
                report.Exam.Age,
                Sex = report.Exam.Patient.Sex switch
                {
                    BusinessObjects.Exams.PatientSex.Female => "女",
                    BusinessObjects.Exams.PatientSex.Male => "男",
                    BusinessObjects.Exams.PatientSex.Other => "不详",
                    _ => null
                },
                report.Exam.Patient.PhoneNumber,
                report.Exam.OutPatientNumber,
                report.Exam.InPatientNumber,
                report.Exam.PhysicalExamNumber,
                report.Exam.BedNumber,
                report.Exam.InPatientArea,
                report.Exam.WardNumber,
                ApplyDepartment = report.Exam.ApplyDepartment?.Name,
                ApplyDoctor = report.Exam.ApplyDoctor?.Name,
                ExamItems = report.Exam.ExamItemsText,
                report.Exam.ClinicalDiagnosis,
                RevisitRecord = report.RevisitRecordJson,
                report.FollowupResult,
                Schema = workflowOutput.View,
                Readonly = readOnly,
                report.ActualRevisitTime,
                report.RevisitTime,
            };
        }
        return workflowOutput;
    }
}
